﻿import os
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.api import mail
from django.utils import simplejson

class UserRss(db.Model):
    user = db.UserProperty()
    name = db.StringProperty()
    url = db.StringProperty()
    date = db.DateTimeProperty(auto_now_add=True)

class MainPage(webapp.RequestHandler):
    def get(self):
        if users.get_current_user():
            path=os.path.join(os.path.dirname(__file__),'index.html')
            self.response.out.write(template.render(path,{"text":"Hello World"}))
        else:
            path=os.path.join(os.path.dirname(__file__),'login.html')
            self.response.out.write(template.render(path,{"url":users.create_login_url(self.request.uri)}))


class Mail(webapp.RequestHandler):
    def post(self):
          sender_address = users.get_current_user().email()
          user_address = self.request.get("email") or "xzkcz@163.com"
          subject = self.request.get("subject") or " 这里是标题"
          body = self.request.get("body")  or  "这里是内容"
          if not mail.is_email_valid(user_address):
              self.response.out.write("收件人邮件地址格式不正确")
          else:
              message = mail.EmailMessage()
              message.sender = sender_address
              message.to = user_address
              message.subject = subject
              message.html = body
              message.send()              
              self.response.out.write(1)


class RssItem(webapp.RequestHandler):
    def get(self):
        url = self.request.get('url')
        callback = self.request.get('callback')
        result = urlfetch.fetch(url=url)        
        content = result.content.decode('utf-8')
        if callback:            
            ret = callback + "('" + content  + "')"
        else:
            ret = content
          
        self.response.out.write(ret)
    def post(self):
        action = self.request.get('action')
        if action == "add":
            self.add()
        elif action == "delete":
            self.delete()
        elif action == "edit":
            self.edit()            
    def delete(self):
        id = self.request.get('id')
        id = int(id)
        rss = UserRss.get_by_id(id)
        if rss:
            rss.delete()
            self.response.out.write(1)
        else:
            self.response.out.write("not existed")
    def edit(self):
        id = self.request.get('id')
        id = int(id)
        rss = UserRss.get_by_id(id)
        if rss:
            rss.name = self.request.get('name')
            rss.url = self.request.get('url')
            rss.put()
            self.response.out.write(1)
        else:
            self.response.out.write("not existed")
    def add(self):
        userRss = UserRss()
        if users.get_current_user():
            userRss.user = users.get_current_user()
            userRss.name = self.request.get('name')
            userRss.url = self.request.get('url')
            userRss.put()
            self.response.out.write(userRss.key().id())
        else:
            self.response.out.write(0)

class RssList(webapp.RequestHandler):
    def get(self):
        resp = []
        if users.get_current_user():
            results = UserRss.all().filter("user =", users.get_current_user())
            for result in results:
                resp.append({"id":result.key().id(), "name":result.name, "url":result.url})        
        self.response.out.write(simplejson.dumps(resp))
                                    
application = webapp.WSGIApplication(
                                        [('/',MainPage), ('/rss_item',RssItem),('/rss_list',RssList),('/mail',Mail)],
                                        debug = True
                                     )
                                     
def main():
    run_wsgi_app(application)
    
if __name__ == "__main__":
    main()